#!/bin/bash

# =============================================
# 达梦 TPC-C 压测脚本 - 参数组2（内存/检查点/提交调优）
# 一键执行：初始化 → 注入参数 → 重启 → 压测 → 收集结果
# 支持 root 执行，自动修复权限
# =============================================

set -e  # 遇错即停

# --- 基础路径配置 ---
BASE_DIR="/dmdata/hql/dm8tpcc/01tpcc"
cd "$BASE_DIR" || { echo "❌ 切换目录失败: $BASE_DIR"; exit 1; }

INIT_SCRIPT="../init_dm8/1initDB.sh"
LOAD_SCRIPT="tpcc_load.sh"
TEST_SCRIPT="tpcc_test.sh"
DM_INI="/dmdata/hql/dmdata_tpcc/DAMENG/dm.ini"
DISQL_CMD="../dm8/bin/disql SYSDBA/Dameng123:5236"
SERVICE_SCRIPT="../init_dm8/DmService"

# --- 创建带时间戳的日志目录 ---
LOG_DIR="param2_test_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$LOG_DIR"
RESULT_LOG="$LOG_DIR/result.log"
touch "$RESULT_LOG"

echo ">>> 日志目录: $LOG_DIR"
echo ">>> 开始时间: $(date '+%Y-%m-%d %H:%M:%S')" | tee -a "$RESULT_LOG"

# --- 检查关键脚本是否存在 ---
[ ! -f "$INIT_SCRIPT" ] && { echo "❌ 初始化脚本不存在: $INIT_SCRIPT"; exit 1; }
[ ! -f "$LOAD_SCRIPT" ] && { echo "❌ 加载脚本不存在: $LOAD_SCRIPT"; exit 1; }
[ ! -f "$TEST_SCRIPT" ] && { echo "❌ 测试脚本不存在: $TEST_SCRIPT"; exit 1; }

# =============================================
# STEP 1: 初始化数据库（使用原 1initDB.sh，但跳过 alterini.py）
# =============================================
echo ">>> [STEP 1] 执行数据库初始化..."
sh "$INIT_SCRIPT"

# --- 【关键】修复权限，确保 dmdba 可访问 ---
echo ">>> 修复数据目录权限 (chown dmdba)..."
chown -R dmdba:dmdba /dmdata/hql/dmdata_tpcc 2>/dev/null || echo ">>> 注意：当前用户非 root，跳过 chown（请确保用 dmdba 执行）"

# =============================================
# STEP 2: 注入参数组2（覆盖任何旧配置）
# =============================================
echo ">>> [STEP 2] 注入参数组2到 dm.ini..." | tee -a "$RESULT_LOG"

declare -A PARAM_CHANGES=(
    ["MEMORY_POOL"]="1500"
    ["BUFFER_POOLS"]="31"
    ["BUFFER_MODE"]="0"
    ["FAST_POOL_PAGES"]="1500"
    ["FAST_ROLL_PAGES"]="1500"
    ["CKPT_RLOG_SIZE"]="20480"
    ["CKPT_INTERVAL"]="60"
    ["CKPT_FLUSH_RATE"]="2"
    ["CKPT_WAIT_PAGES"]="1024"
    ["FORCE_FLUSH_PAGES"]="8"
    ["COMMIT_BATCH"]="10"
    ["COMMIT_WRITE"]="IMMEDIATE,WAIT"
    ["THRDS_POOL_INIT"]="150"
    ["COMMIT_BATCH_TIMEOUT"]="3"
)

# 确保 dm.ini 存在
[ ! -f "$DM_INI" ] && { echo "❌ dm.ini 不存在: $DM_INI"; exit 1; }

# 删除旧参数行，注入新值
for param in "${!PARAM_CHANGES[@]}"; do
    sed -i "/^[[:space:]]*$param[[:space:]]*=/d" "$DM_INI"
    echo "$param = ${PARAM_CHANGES[$param]}" >> "$DM_INI"
    echo "    $param = ${PARAM_CHANGES[$param]}" | tee -a "$RESULT_LOG"
done

echo ">>> 参数注入完成。" | tee -a "$RESULT_LOG"

# =============================================
# STEP 3: 重启数据库服务
# =============================================
echo ">>> [STEP 3] 重启数据库服务..." | tee -a "$RESULT_LOG"
"$SERVICE_SCRIPT" restart
sleep 40  # 等待服务完全启动

# 验证数据库是否可连接
echo ">>> 验证数据库连接..."
$DISQL_CMD -q <<EOF | grep "login success" >/dev/null
select 1;
EOF
if [ $? -ne 0 ]; then
    echo "❌ 数据库连接失败，请检查服务状态！"
    exit 1
fi
echo ">>> 数据库连接成功。" | tee -a "$RESULT_LOG"

# =============================================
# STEP 4: 执行 TPC-C 加载与测试
# =============================================
echo ">>> [STEP 4] 加载 TPC-C 数据..." | tee -a "$RESULT_LOG"
sh "$LOAD_SCRIPT"

echo ">>> [STEP 5] 执行 TPC-C 压测..." | tee -a "$RESULT_LOG"
sh "$TEST_SCRIPT"

# =============================================
# STEP 6: 收集压测结果
# =============================================
echo ">>> [STEP 6] 收集压测结果..." | tee -a "$RESULT_LOG"

# --- 当前参数值 ---
echo "=== 当前关键参数值 ===" >> "$RESULT_LOG"
for param in "${!PARAM_CHANGES[@]}"; do
    current_val=$($DISQL_CMD -q <<EOF | tail -n 1
select para_value from v\$dm_ini where para_name = '$param';
EOF
)
    echo "$param = $current_val" >> "$RESULT_LOG"
done

# --- NUMA 统计 ---
echo "=== NUMA STAT ===" >> "$RESULT_LOG"
numastat -p $(pidof dmserver) 2>/dev/null | sed -n "10p;19p;28p" >> "$RESULT_LOG" || echo "NUMA 获取失败" >> "$RESULT_LOG"

# --- 分区表数量 ---
echo "=== 分区表数量 ===" >> "$RESULT_LOG"
$DISQL_CMD -q <<EOF | tail -n 1 >> "$RESULT_LOG"
select count(*) from dba_tab_partitions;
EOF

# --- trx4_cmt 日志 ---
echo "=== trx4_cmt 日志（最后200行）===" >> "$RESULT_LOG"
LOG_FILE="../dm8/log/dm_DMSERVER_$(date +%Y%m).log"
if [ -f "$LOG_FILE" ]; then
    tail -n 200 "$LOG_FILE" | grep "trx4_cmt" >> "$RESULT_LOG"
else
    echo "日志文件不存在: $LOG_FILE" >> "$RESULT_LOG"
fi

# --- TPC-C 结果 ---
echo "=== TPC-C 性能结果 ===" >> "$RESULT_LOG"
LATEST_LOG=$(ls -lort log/01_tpcc/ 2>/dev/null | tail -n 1 | awk '{print $NF}' 2>/dev/null)
if [ -n "$LATEST_LOG" ] && [ -f "log/01_tpcc/$LATEST_LOG" ]; then
    grep -A 4 "Measured tpmC (NewOrders)" "log/01_tpcc/$LATEST_LOG" >> "$RESULT_LOG"
else
    echo "未找到TPC-C测试日志" >> "$RESULT_LOG"
fi

# --- 提取 tpmC 值 ---
tpmc_line=$(grep -A1 "NewOrders" "$RESULT_LOG" 2>/dev/null | tail -n 1)
tpmc_clean=$(echo "$tpmc_line" | awk '{print $1}' | tr -d ',')
echo ">>> 最终 tpmC: ${tpmc_clean:-N/A}" | tee -a "$RESULT_LOG"

# --- 结束时间 ---
echo ">>> 结束时间: $(date '+%Y-%m-%d %H:%M:%S')" | tee -a "$RESULT_LOG"
echo "✅ 压测完成！结果保存至: $RESULT_LOG"
